<template>
  <div class="total">
    <r-table
      :isSelection="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="pagination"
      :isHandle="true"
      @refresh="page()"
    >
    </r-table>
    <!--  Recharge、消费钱包流水明细  -->
    <el-dialog
      :visible.sync="particularsShow"
      :title="
        chargeMoney === '1'
          ? 'Recharge' + ' Money Flowing Details'
          : 'Consumption' + ' Money Flowing Details'
      "
      width="850px"
      top="5vh"
    >
      <div>
        <span class="rechargeSelect">
          <el-select
            placeholder="Please Select"
            :clearable="true"
            v-model="chargeMoney"
            style="width:20%"
            size="small"
          >
            <el-option
              v-for="item in userNumValue"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </span>
        <el-table :data="tableDatas" style="width: 100%" class="rechargeTable">
          <el-table-column align="center" prop="money" label="Money"
            ><template slot-scope="scope">{{
              scope.row.money ? "$" + scope.row.money.toFixed(2) : "--"
            }}</template></el-table-column
          >
          <el-table-column align="center" prop="type" label="Type">
            <template slot-scope="scope">{{
              scope.row.type == 1 ? "Recharge" : "Consumption"
            }}</template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="Remarks" />
          <el-table-column
            align="center"
            prop="joinValue"
            label="Flowing Number"
          />
          <el-table-column align="center" prop="orderNo" label="Order Number" />
          <el-table-column align="center" prop="ctime" label="Creation Time" />
        </el-table>
        <div class="showAll_dialog">
          <el-pagination
            v-model:current-page="paginations.page"
            v-model:page-size="paginations.size"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginations.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>
    <!-- 平台Recharge Amount -->
    <el-dialog title="Recharge" :visible.sync="renewalShow" width="27%">
      <el-form
        :model="renewalData"
        :status-icon="true"
        :rules="renewalRules"
        ref="renewalData"
        label-width="110px"
        class="renewalData"
      >
        <el-form-item v-if="isFalse" label="OperatorID" prop="operatorId">
          <el-input :disabled="true" v-model="renewalData.operatorId" />
        </el-form-item>
        <el-form-item label="Recharge Amount($)" prop="money">
          <el-input type="number" v-model="renewalData.money" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewalShow = false">Cancel</el-button>
        <el-button type="primary" @click="renewalSubmit('renewalData')"
          >Confirm</el-button
        >
      </div>
    </el-dialog>
    <!-- WeChatRechargeQR Code -->
    <el-dialog
      title="WeChat Mode Recharge"
      :visible.sync="renewalShows"
      width="500px"
    >
      <el-form
        :model="renewalDatas"
        :status-icon="true"
        :rules="renewalRuless"
        ref="renewalDatas"
        label-width="110px"
        class="renewalData"
      >
        <el-form-item
          label="Recharge Amount($)"
          prop="money"
          label-width="160px"
        >
          <el-input type="number" v-model="renewalDatas.money" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewalShows = false">Cancel</el-button>
        <el-button type="primary" @click="renewalSubmits('renewalDatas')"
          >Confirm</el-button
        >
      </div>
    </el-dialog>
    <!-- WeChatRecharge付款码 -->
    <el-dialog
      :visible.sync="renewalShowss"
      :show-close="false"
      :center="true"
      :destroy-on-close="true"
      width="350px"
      top="27vh"
    >
      <div style="position: relative;top: -20px">
        {{ count }}After Seconds Payment Code Expires
      </div>
      <img
        style="height:100%;width: 100%;position: relative;top: -10px;left: 8px;"
        :src="captchaPath"
      />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkToFixedTwo = (rule, value, callback) => {
      const reg = /[^\d]/g;
      if (!reg.test(value)) {
        callback();
      } else {
        return callback(new Error("Please Input Integer Number"));
      }
    };
    return {
      //流水明细
      chargeMoney: "1",
      oID: "",
      userNumValue: [
        {
          value: "1",
          name: "Recharge"
        },
        {
          value: "2",
          name: "Consumption"
        }
      ],
      tableDatas: [], //流水明细
      paginations: { size: 10, page: 1, total: 0 }, //流水分页
      particularsShow: false, //Control流水明细显示隐藏
      // Recharge Amount
      renewalShow: false,
      renewalData: {
        operatorId: "",
        money: 0
      },
      isFalse: false,
      renewalRules: {
        operatorId: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        money: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      // WeChatQR CodeMoney
      renewalShows: false,
      renewalDatas: {
        money: ""
      },
      renewalRuless: {
        money: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      captchaPath: "",
      renewalShowss: false,
      timer: null,
      payS: false,
      count: 120, //倒计时秒数
      Times: null,
      // table表格
      tableData: [{}],
      tableCols: [
        { label: "Operator", prop: "operatorName" },
        // { label: "QR Code", type: "image", prop: "qrCode" },
        {
          label: "Usable Balance",
          prop: "balance",
          formatter: e => "$" + e.balance
        },
        {
          label: "Total Recharge Balance",
          prop: "totalBalance",
          formatter: e => "$" + e.totalBalance
        },
        { label: "Creation Time", prop: "ctime" },
        { label: "End Time", prop: "utime" },
        {
          label: "Operations",
          type: "button",
          width: 200,
          btnList: [
            {
              label: "Detail",
              type: "primary",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: async row => {
                this.particularsShow = true;
                this.oID = row.operatorId;
                this.chargeMoney = "1";
                this.walletFlowFn(this.oID, this.chargeMoney);
              }
            },
            {
              label: "Platform Recharge",
              type: "primary",
              plain: true,
              handle: row => {
                this.renewalShow = true;
                this.renewalData.operatorId = row.operatorId;
                this.renewalData.money = 0;
              },
              isShow: () => {
                return sessionStorage.getItem("role") === "admin"
                  ? true
                  : false;
              }
            },
            {
              label: "WeChat Recharge",
              type: "primary",
              plain: true,
              handle: row => {
                this.renewalShows = true;
                this.renewalDatas.money = "";
              },
              isShow: () => {
                return sessionStorage.getItem("role") === "operator"
                  ? true
                  : false;
              }
            }
          ]
        }
      ],
      // 分页
      pagination: { limit: 10, offset: 1, total: 0 }
    };
  },
  mounted() {
    this.getData();
  },
  watch: {
    chargeMoney: {
      handler(newValue, oldValue) {
        // console.log('新值：', newValue, '旧值：', oldValue)
        if (newValue) {
          this.zeroFn();
          this.walletFlowFn(this.oID, newValue);
        }
      },
      deep: true // 深度监听
    },
    renewalShowss: {
      handler(newValue, oldValue) {
        // console.log('新值：', newValue, '旧值：', oldValue)
        if (!newValue && !this.payS) {
          clearInterval(this.timer);
          this.$message({
            message: "Payment Unfinished",
            type: "error"
          });
        } else if (!newValue && this.payS) {
          // console.log('PaymentSuccess执行的监听');
        }
      },
      deep: true // 深度监听
    }
  },
  methods: {
    zeroFn() {
      this.paginations.size = 10;
      this.paginations.page = 1;
      this.paginations.total = 0;
    },
    // 倒计时
    setTimeoutFn() {
      this.count = 120;
      this.Times = setInterval(() => {
        if (this.count === 0) {
          this.count = 0;
          clearInterval(this.Times);
          this.renewalShowss = false;
          return false;
        }
        this.count = this.count - 1;
      }, 1000);
    },
    // 表格Data
    async getData() {
      // 如果是总平台账号就获取总的钱包列表
      if (sessionStorage.getItem("role") === "admin") {
        let res = await this.apis.operatorWalletList({
          pageNum: this.pagination.offset,
          pageSize: this.pagination.limit
        });
        this.tableData = res.rows || [];
        this.pagination.total = res.total;
      } else if (sessionStorage.getItem("role") === "operator") {
        // 如果是Operator账号就获取单个Operator个人的钱包
        let res = await this.apis.operatorWalletGetWallet();
        this.tableData = [res.data] || [];
        this.pagination.total = this.tableData.length || 0;
      }
    },
    // 钱包流水明细
    async walletFlowFn(operatorId, type) {
      let page = {
        operatorId: operatorId,
        pageNum: this.paginations.page,
        pageSize: this.paginations.size,
        type: type || "1" //1 Recharge  2 消费
      };
      let res = await this.apis.operatorWalletRecordList(page);
      this.tableDatas = res.rows || [];
      this.paginations.total = res.total || 0;
    },
    // 平台Recharge Amount
    async renewalSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.renewalData.money === 0) {
            this.$message({
              message: "Recharge Amount Greater Than 0",
              type: "error"
            });
            return false;
          } else {
            this.renewalData.money = Number(this.renewalData.money);
          }
          let res = await this.apis.operatorWalletPtRecharge(this.renewalData);
          // console.log(444, this.renewalData, res);
          this.$message({
            message: res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.renewalShow = false;
          this.getData();
        }
      });
    },
    // WeChatRecharge Amount
    async renewalSubmits(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (
            Number(this.renewalDatas.money) === 0 ||
            Number(this.renewalDatas.money) < 0
          ) {
            this.$message({
              message: "Recharge Amount Greater Than 0",
              type: "error"
            });
            return false;
          }
          let res = await this.apis.operatorWalletScanRecharge(
            this.renewalDatas
          );
          this.$message({
            message:
              res.code == 200
                ? "Input Recharge Amount Success,Wechat Payment Code Is About To Open..."
                : res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.renewalShows = false;
          this.getData();
          //WeChatQR CodeRecharge接口调Success后打开WeChat付款QR Code
          setTimeout(() => {
            if (res.code == 200) {
              this.captchaPath = "data:image/jpeg;base64," + res.data;
              this.renewalShowss = true;
              this.setTimeoutFn();
              let pa = res.msg || "";

              this.timer && clearInterval(this.timer);
              this.timer = setInterval(async () => {
                let OrderResult = await this.apis.operatorWalletGetRechargeResult(
                  pa
                );
                // console.log('Payment结果查询', OrderResult);
                if (OrderResult.data === 1) {
                  clearInterval(this.timer);
                  this.$message({
                    message: "Payment Complete",
                    type: "success"
                  });
                  this.payS = true;
                  this.renewalShowss = false;
                  setTimeout(() => {
                    this.payS = false;
                  }, 2000);
                  this.getData();
                } else if (OrderResult.data === 0) {
                  // console.log('Payment未完成');
                }
              }, 2000);
            }
          }, 1000);
        }
      });
    },
    // Current页的条数
    handleSizeChange(val) {
      this.paginations.size = val;
      this.walletFlowFn(this.oID, this.chargeMoney);
    },
    // Current页
    handleCurrentChange(val) {
      this.paginations.page = val;
      this.walletFlowFn(this.oID, this.chargeMoney);
    },
    // 切换分页重新获取表格
    page() {
      this.getData();
    }
  }
};
</script>

<style scoped lang="scss">
.total {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.agentIdClass {
  margin-bottom: 20px;
}

.agentIdClass > .el-select {
  margin-left: 8%;
}

.agentIdClass1 > .el-select {
  margin-left: 11%;
}

.w54MB20 {
  width: 76%;
  margin-bottom: 10px;
}

.fJ {
  float: auto;
}

.rechargeSelect {
  position: relative;
  top: -68px;
  left: 300px;
}

.rechargeTable {
  position: relative;
  top: -45px;
}
</style>
